package eerbaar.shared.persist.internal.lib;

import java.util.ArrayList;
import java.util.List;

import eerbaar.expression.IExpression;
import eerbaar.level.IComplete;
import eerbaar.level.LevelFactory;
import eerbaar.shared.exceptions.GameException;
import eerbaar.shared.exceptions.GameRuntimeException;
import eerbaar.shared.persist.IPersistService;
import eerbaar.shared.persist.IPersister;
import eerbaar.shared.persist.ISaver;
import eerbaar.shared.service.ServiceFactory;
import eerbaar.shared.tree.IAttributes;
import eerbaar.shared.tree.INode;
import eerbaar.shared.tree.NodeCmdFactory;

public class CompletePersister implements IPersister<IComplete> {

    public static final String NAME = "complete";

    private IComplete target;

    public CompletePersister() {
        //
    }

    public CompletePersister(IComplete target) {
        assert (target != null);

        this.target = target;
    }

    public CompletePersister(INode node) throws GameRuntimeException {
        load(node);
    }

    @Override
    public Class<IComplete> getRegistertedInterface() {
        return IComplete.class;
    }

    @Override
    public ISaver<?>[] getSavableChildren() {

        List<ExpressionPersister> result = new ArrayList<ExpressionPersister>();

        IExpression[] a = this.target.getExpressions();
        for (IExpression e : a) {
            ExpressionPersister p = new ExpressionPersister(e);
            result.add(p);
        }

        return result.toArray(new ExpressionPersister[] {});
    }

    @Override
    public String getSavableName() {

        return NAME;
    }

    @Override
    public IComplete getTarget() {

        return this.target;
    }

    @Override
    public boolean isAssignableFrom(ISaver<?> saver) {

        return false;
    }

    @Override
    public IComplete load(INode node) {
        assert (node != null);

        IComplete result = LevelFactory.createComplete();

        IAttributes a = node.getAttributes();
        int next = a.get(Integer.class, "next");
        result.setNext(next);

        IPersistService service = ServiceFactory
                .getService(IPersistService.class);

        List<INode> list = NodeCmdFactory.findChildren(node,
                ExpressionPersister.NAME);
        for (INode n : list) {
            try {
                IExpression obj = service.load(IExpression.class, n);
                result.addExpression(obj);
            } catch (GameException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    @Override
    public void saveAttributes(INode node) {

        IAttributes a = node.getAttributes();

        int next = this.target.getNext();
        a.set(Integer.class, "next", next);
    }

    @Override
    public void setTarget(IComplete obj) {

        this.target = obj;
    }

}
